﻿using System.Collections;
using System.Configuration;
using System.Data;
using System.Web.Security;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.UI;

using UsersTableAdapters;

using System.DirectoryServices;

/// <summary>
/// Summary description for UsersBLL
/// </summary>

[System.ComponentModel.DataObject]
public class UsersBLL
{
    ILE_Global ileGlobal = new ILE_Global();

    private UsersTableAdapter _usersAdapter = null;
    protected UsersTableAdapter UsersAdapter
    {
        get
        {
            if (_usersAdapter == null)
                _usersAdapter = new UsersTableAdapter();

            return _usersAdapter;
        }
    }

    private Users_NonInstituteTableAdapter _nonInstituteUserAdapter = null;
    protected Users_NonInstituteTableAdapter NonInstituteUsersAdapter
    {
        get
        {
            if (_nonInstituteUserAdapter == null)
                _nonInstituteUserAdapter = new Users_NonInstituteTableAdapter();

            return _nonInstituteUserAdapter;
        }
    }

    private Users_NonInstitute_ActivationTableAdapter _nonInstituteUserActivationAdapter = null;
    protected Users_NonInstitute_ActivationTableAdapter NonInstituteUserActivationsAdapter
    {
        get
        {
            if (_nonInstituteUserActivationAdapter == null)
                _nonInstituteUserActivationAdapter = new Users_NonInstitute_ActivationTableAdapter();

            return _nonInstituteUserActivationAdapter;
        }
    }

    private Relations_Course_UserTableAdapter _relationsCourseUserAdapter = null;
    protected Relations_Course_UserTableAdapter RelationsCourseUserAdapter
    {
        get
        {
            if (_relationsCourseUserAdapter == null)
                _relationsCourseUserAdapter = new Relations_Course_UserTableAdapter();

            return _relationsCourseUserAdapter;
        }
    }


    [System.ComponentModel.DataObjectMethodAttribute
        (System.ComponentModel.DataObjectMethodType.Select, true)]
    public Users.UsersDataTable GetAllUsers()
    {
        return UsersAdapter.GetUsers();
    }

    [System.ComponentModel.DataObjectMethodAttribute
        (System.ComponentModel.DataObjectMethodType.Select, false)]
    public Users.UsersRow GetUserByUserID(int UserID)
    {
        try
        {
            return UsersAdapter.GetUserByUserID(UserID)[0];
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("UsersBLL:GetUserByUserID:000 - GetUser Failed", ex, HttpContext.Current.Request.Url.PathAndQuery.ToString(), 4);
            return null;
        }
    }

    public Users.UsersRow GetUserByUsername(string Username)
    {
        try
        {
            return UsersAdapter.GetUserByUsername(Username)[0];
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("UsersBLL:GetUserByUsername:000 - GetUser Failed", ex, 3);
            return null;
        }
    }

    [System.ComponentModel.DataObjectMethodAttribute
        (System.ComponentModel.DataObjectMethodType.Select, false)]
    public Users._Relations_Course_UserDataTable GetCourseUserRelationshipsByCourseIDAndUserIDAndType(int CourseID, int UserID, string Type)
    {
        try
        {
            return RelationsCourseUserAdapter.GetCourseUserRelationsByCourseIDAndUserIDAndType(CourseID, UserID, Type);
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("UsersBLL:GetCourseUserRelationshipsByCourseIDAndUserIDAndType:000 - GetCourseUserRelationsByCourseIDAndUserID Failed", ex, 4);
            return null;
        }
    }

    [System.ComponentModel.DataObjectMethodAttribute
        (System.ComponentModel.DataObjectMethodType.Select, false)]
    public Users._Relations_Course_UserDataTable GetCourseUserRelationshipsByCourseIDAndSectionNumber(int CourseID, int SectionNumber)
    {
        try
        {
            return RelationsCourseUserAdapter.GetCourseUserRelationsByCourseIDAndSectionNumber(CourseID, SectionNumber);
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("UsersBLL:GetCourseUserRelationshipsByCourseIDAndSectionNumber:000 - GetCourseUserRelationsByCourseIDAndSectionNumber Failed", ex, 4);
            return null;
        }
    }

    [System.ComponentModel.DataObjectMethodAttribute
        (System.ComponentModel.DataObjectMethodType.Select, false)]
    public Users._Relations_Course_UserDataTable GetCourseUserRelationshipsByCourseIDAndSectionNumberAndType(int CourseID, int SectionNumber, string Type)
    {
        try
        {
            return RelationsCourseUserAdapter.GetCourseUserRelationsByCourseIDAndSectionNumberAndType(CourseID, SectionNumber, Type);
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("UsersBLL:GetCourseUserRelationshipsByCourseIDAndSectionNumberAndType:000 - GetCourseUserRelationshipsByCourseIDAndSectionNumberAndType Failed", ex, 4);
            return null;
        }
    }

    [System.ComponentModel.DataObjectMethodAttribute
        (System.ComponentModel.DataObjectMethodType.Select, false)]
    public Users._Relations_Course_UserRow GetCourseUserRelationshipsByCourseIDAndSectionNumberAndUserID(int CourseID, int SectionNumber, int UserID)
    {
        try
        {
            return RelationsCourseUserAdapter.GetCourseUserRelationsByCourseIdAndSectionNumberAndUserId(CourseID, SectionNumber, UserID)[0];
        }
        catch (Exception ex)
        {
            //ileGlobal.RecordError("UsersBLL:GetCourseUserRelationsByCourseIdAndSectionNumberAndUserId:000 - Failed", ex, 2);
            return null;
        }
    }

    [System.ComponentModel.DataObjectMethodAttribute
        (System.ComponentModel.DataObjectMethodType.Select, false)]
    public Users._Relations_Course_UserDataTable GetCourseUserRelationshipsByUserIdAndType(int UserID, string Type)
    {
        try
        {
            return RelationsCourseUserAdapter.GetCourseUserRelationsByUserIdAndType(UserID, Type);
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("UsersBLL:GetCourseUserRelationshipsByUserIdAndType:000 - Failed", ex, 4);
            return null;
        }
    }

    [System.ComponentModel.DataObjectMethodAttribute
        (System.ComponentModel.DataObjectMethodType.Select, false)]
    public Users.UsersDataTable GetUsersByAccountType(string AccountType)
    {
        try
        {
            return UsersAdapter.GetUsersByAccountType(AccountType);
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("UsersBLL:GetUsersByAccountType:000 - GetUsersByAccountType Failed", ex, 4);
            return null;
        }
    }

    [System.ComponentModel.DataObjectMethodAttribute
        (System.ComponentModel.DataObjectMethodType.Select, false)]
    public Users.Users_NonInstituteRow GetNonInstUserByUserID(int UserID)
    {
        try
        {
            return NonInstituteUsersAdapter.GetUserByUserID(UserID)[0];
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("UsersBLL:GetNonInstUserByUserID:000", ex, 4);
            return null;
        }
    }

    [System.ComponentModel.DataObjectMethodAttribute
        (System.ComponentModel.DataObjectMethodType.Insert, false)]
    public int InsertUser(string username, string accountType, string firstName, string lastName, string studentIDNumber, string email, int studentYear)
    {
        return Convert.ToInt32(UsersAdapter.InsertUser(username, accountType, firstName, lastName, email, studentIDNumber, studentYear, true));
    }

    [System.ComponentModel.DataObjectMethodAttribute
        (System.ComponentModel.DataObjectMethodType.Insert, false)]
    public bool InsertCourseUserRelation(int CourseID, int SectionNumber, int UserID, string AccountType, int SortOrder)
    {
        return RelationsCourseUserAdapter.Insert(CourseID, SectionNumber, UserID, AccountType, SortOrder) == 1;
    }

    [System.ComponentModel.DataObjectMethodAttribute
        (System.ComponentModel.DataObjectMethodType.Update, true)]
    public bool UpdateUserByUserID(string username, string accountType, string firstName, string lastName, string studentIDNumber, string email, int studentYear, bool isEnabled, int userID)
    {
        return UsersAdapter.UpdateUserByUserID(username, accountType, firstName, lastName, email, studentIDNumber, studentYear, isEnabled, userID) == 1;
    }

    [System.ComponentModel.DataObjectMethodAttribute
        (System.ComponentModel.DataObjectMethodType.Update, false)]
    public bool UpdateUserByUsername(string accountType, string firstName, string lastName, string studentIDNumber, string email, bool isEnabled, int studentYear, string username)
    {
        return UsersAdapter.UpdateUserByUsername(accountType, firstName, lastName, email, studentIDNumber, studentYear, isEnabled, username) == 1;
    }

    [System.ComponentModel.DataObjectMethodAttribute
        (System.ComponentModel.DataObjectMethodType.Update, false)]
    public bool ResetNonInstitutUserPassword(string Email, string SecurityAnswer, string NewPassword)
    {
        try
        {
            Users.Users_NonInstituteDataTable users = NonInstituteUsersAdapter.GetUserByUsername(Email);
            if(users.Count == 0)
            {
                return false;
            }

            //if(true)
            if (users[0].SecurityAnswer.ToLower() == SecurityAnswer.ToLower())
            {
                Users.UsersRow user = UsersAdapter.GetUserByUserID(users[0].UserID)[0];

                MailAddressCollection receiver = new MailAddressCollection();
                receiver.Add(Email);
                ileGlobal.SendEmail(receiver, "ILE@wsu.edu", "ILE - Your Password has been reset.", "Your Password for Information Literacy Education has been reset.");

                NewPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(NewPassword, "sha1");
                NonInstituteUsersAdapter.UpdatePassword(NewPassword, user.UserID);

                return true;
            }
            else
            {
                return false;
            }
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("UsersBLL:ResetNonInstitutUserPassword:000", ex, 3);
            return false;
        }
    }

    [System.ComponentModel.DataObjectMethodAttribute
        (System.ComponentModel.DataObjectMethodType.Select, false)]
    public int IsUserInTable(string Username)
    {
        try
        {
            if (Convert.ToInt32(UsersAdapter.IsUserInTable(Username)) == 1)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("UsersBLL:IsUserInTable:000 - Count User Failed", ex, 3);
            return -1;
        }
    }

    [System.ComponentModel.DataObjectMethodAttribute
           (System.ComponentModel.DataObjectMethodType.Insert, false)]
    public int InsertNonInstitutUser(string username, string password, string accountType,
        string firstName, string lastName, string organization, int studentYear,
        string securityQuestion, string securityAnswer)
    {
        try
        {
            // Insert Regular User Information First
            int UserID = Convert.ToInt32(UsersAdapter.InsertUser(username, accountType, firstName, lastName, username, String.Empty, studentYear, false));

            // Then Insert Student (Institut User) Inforamtion
            // IF this fails, record error and delete user from Users table.
            if (NonInstituteUsersAdapter.InsertNonInstituteInfo(UserID, password, organization, securityQuestion, securityAnswer) != 1)
            {
                ileGlobal.RecordError("UsersBLL:InsertNonInstitutUser:000  Inserting Non-Institut User Info Failed.", "No Detail Available", 4);
                UsersAdapter.DeleteUser(UserID);
                return 0;
            }
            else
            {
                ILE_Config ileConfig = new ILE_Config();
                string ActivationCode = String.Empty;
                Random random = new Random();
                for (int i = 0; i <= 12; i++)
                {
                    ActivationCode += random.Next(99).ToString();
                }

                NonInstituteUserActivationsAdapter.InsertActivationCode(UserID, ActivationCode);

                MailAddress receiver = new MailAddress(username);
                MailAddressCollection receivers = new MailAddressCollection();
                receivers.Add(receiver);
                // *SteveMsg
                string _EmailBody = "You have created an account for Information Literacy Education (ILE). <br /><a href=''>Click here to Activate your account</a><br />Activation Code : " + ActivationCode;
                ileGlobal.SendEmail(receivers, ileConfig.getDefaultEmailSenderAddress().ToString(), "ILE Account Activation",
                    _EmailBody);
                return UserID;
            }
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("UsersBLL:InsertNonInstitutUser:001 - Insert User Failed", ex, 3);
            return 0;
        }
    }

    [System.ComponentModel.DataObjectMethodAttribute
        (System.ComponentModel.DataObjectMethodType.Select, false)]
    public bool AuthenticateNonInstitutUser(string Username, string Password)
    {
        try
        {
            string hashedPassword = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(Password, "sha1");
            return (NonInstituteUsersAdapter.Authentication(Username, hashedPassword) == 1);
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("UsersBLL:AuthenticateNonInstitutUser:000 - NonInstitutUser Authentication process Failed", ex, 3);
            return false;
        }
    }

    [System.ComponentModel.DataObjectMethodAttribute
        (System.ComponentModel.DataObjectMethodType.Delete, true)]
    public bool DeleteUserByUserID(int UserID)
    {
        try
        {
            return UsersAdapter.DeleteUser(UserID) == 1;
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("UsersBLL:DeleteUserByUserID:000", ex, 3);
            return false;
        }
    }

    [System.ComponentModel.DataObjectMethodAttribute
        (System.ComponentModel.DataObjectMethodType.Delete, false)]
    public bool DeleteCourseUserRelationsByCourseIDAndUserIDAndType(int CourseID, int UserID, string Type)
    {
        try
        {
            return RelationsCourseUserAdapter.DeleteCourseUserRelationsByCourseIDAndUserIDAndType(CourseID, UserID, Type) > 0;
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("UsersBLL:DeleteCourseUserRelationByCourseIDAndUserIDAndAccountType:000", ex, 3);
            return false;
        }
    }

    [System.ComponentModel.DataObjectMethodAttribute
        (System.ComponentModel.DataObjectMethodType.Delete, false)]
    public bool DeleteCourseUserRelationsByCourseIDAndSectionNumberAndUserID(int CourseID, int SectionNumber, int UserID)
    {
        try
        {
            return RelationsCourseUserAdapter.Delete(CourseID, SectionNumber, UserID) > 0;
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("UsersBLL:DeleteCourseUserRelationByCourseIDAndUserIDAndAccountType:000", ex, 3);
            return false;
        }
    }

    [System.ComponentModel.DataObjectMethodAttribute
        (System.ComponentModel.DataObjectMethodType.Select, false)]
    public bool ActivateNonInstituteUser(string Username, string ActivationCode)
    {
        Users.UsersRow user = UsersAdapter.GetUserByUsername(Username)[0];
        return NonInstituteUsersAdapter.Activation(user.UserID, ActivationCode) == 1;
    }

    [System.ComponentModel.DataObjectMethodAttribute
        (System.ComponentModel.DataObjectMethodType.Select, false)]
    public Users.Users_NonInstitute_ActivationRow GetActivationCode(int UserID)
    {
        return NonInstituteUserActivationsAdapter.GetActivationCode(UserID)[0];
    }


}

